package net.wofly.sale.stock.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import net.wofly.common.condition.Condition;
import net.wofly.common.condition.ConditionRelate;
import net.wofly.common.condition.ConditionUtil;
import net.wofly.common.condition.FilterCondition;
import net.wofly.common.condition.Operation;
import net.wofly.common.condition.Order;
import net.wofly.common.condition.OrderCondition;
import net.wofly.common.json.XiNiaoJSON;
import net.wofly.common.persistence.PageWrapper;
import net.wofly.common.util.Identities;
import net.wofly.common.util.PageHelper;
import net.wofly.common.util.ResultCode;
import net.wofly.framework.util.ReturnBean;
import net.wofly.right.domain.Organization;
import net.wofly.right.domain.User;
import net.wofly.right.domain.UserRole;
import net.wofly.right.service.IOrganizationService;
import net.wofly.right.service.IRoleService;
import net.wofly.right.service.IUserRoleService;
import net.wofly.right.service.IUserService;
import net.wofly.sale.commodity.domain.CommodityTerminal;
import net.wofly.sale.commodity.service.ICommodityTmlService;
import net.wofly.sale.report.domain.ResourceAskDTO;
import net.wofly.sale.stock.domain.ResourceAsk;
import net.wofly.sale.stock.domain.ResourceAskList;
import net.wofly.sale.stock.domain.Stock;
import net.wofly.sale.stock.domain.Warehouse;
import net.wofly.sale.stock.dto.ResourceAskStatusDTO;
import net.wofly.sale.stock.flow.IResourceAskFlowService;
import net.wofly.sale.stock.repository.ResourceAskRepository;
import net.wofly.sale.stock.service.IInStockService;
import net.wofly.sale.stock.service.IResourceAskListService;
import net.wofly.sale.stock.service.IResourceAskService;
import net.wofly.sale.stock.service.IStockService;
import net.wofly.sale.stock.service.IWarehouseService;
import net.wofly.sale.stock.util.ResourceAskStatus;

@Service("iResourceAskService")
@Transactional
public class ResourceAskServiceImpl implements IResourceAskService {

    private static final Logger logger = LoggerFactory.getLogger(ResourceAskServiceImpl.class);
    
    @Autowired
    ResourceAskRepository resourceAskRepository;
    
    @Autowired
    IResourceAskListService iResourceAskListService;
    
    @Autowired
    ICommodityTmlService  iCommodityTmlService;
    
    @Autowired
    IUserService  iUserService;
    
    @Autowired
    IRoleService iRoleService ;
    
    @Autowired
    IUserRoleService  iUserRoleService;
    
    @Autowired
    IResourceAskFlowService  iResourceAskFlowService;

    @Autowired
    IStockService iStockService;

    @Autowired
    IWarehouseService iWarehouseService;
    
    @Autowired
    IInStockService iInStockService ;
    
    @Autowired
    IOrganizationService iOrganizationService ;
    
    @Override
    public ResourceAsk save(ResourceAsk entity) {
        return resourceAskRepository.save(entity);
    }
    
    @Override
    public void delete(ResourceAsk entity) {
        resourceAskRepository.delete(entity);
    }
    
    @Override
    public void delete(String key) {
        resourceAskRepository.delete(key);
    }
    
    @Override
    public ResourceAsk findOne(String key) {
        return resourceAskRepository.findOne(key);
    }
    
    @Override
    public List<ResourceAsk> save(List<ResourceAsk> entityList) {
        return (List<ResourceAsk>) resourceAskRepository.save(entityList);
    }
    
    @Override
    public ReturnBean<String> checkResourceAsk(String resourceAskID, Integer checkStatus, String checker) {
        ResourceAsk resourceAsk = findOne(resourceAskID);
        if (resourceAsk == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "传入ID值不正确，未找到领料记录");
        }
        //TODO 判断是否有审核权限 ， 同时哪些角色的用户有审核权限
        
        resourceAsk.setStatus(checkStatus);
        resourceAsk.setCheckTime(System.currentTimeMillis());
        save(resourceAsk);
        return new ReturnBean<>(ResultCode.SUCCESS, "审核成功");
    }
    
    @Override
    public ReturnBean<String> commitResourceAsk(String resourceAskID, String commiter) {
        ResourceAsk resourceAsk = findOne(resourceAskID);
        if (resourceAsk == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "传入ID值不正确，未找到领料记录");
        }
        if (resourceAsk.getStatus().intValue() != ResourceAskStatus.草稿.getValue()) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "非草稿状态的领料申请不能提交审核");
        }
        String asker = resourceAsk.getAsker();
        if (!asker.equals(commiter)) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "您无权提交改申请单进行审核");
        }
        
        //	判断当前用户为员工，且其有为仓库时，才可以领料
        User askerUser = iUserService.findOne(asker);
        String firstPosition = askerUser.getRoleID().substring(0,1);
        if (!"1".equals(firstPosition)) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "当前用户不是员工，不可以领料！");
        } else if(1 != askerUser.getWarehouseFlag()){
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "当前用户没有仓库，不可以领料！");
        }
        resourceAsk.setStatus(ResourceAskStatus.待审批.getValue());
        save(resourceAsk);

        return new ReturnBean<>(ResultCode.SUCCESS, "提交成功");
    }
    
    /**
     * 发货
     *
     * @param resourceAskID
     * @param consigner
     * @return
     */
    @Override
    public ReturnBean<String> consign(String resourceAskID, String consigner) {
        ResourceAsk resourceAsk = findOne(resourceAskID);
        if (resourceAsk == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "传入ID值不正确，为找到领料记录");
        }
        if (resourceAsk.getStatus().intValue() != ResourceAskStatus.审核通过.getValue()) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "非审核通过状态的领料申请不能发货");
        }
        resourceAsk.setConsigner(consigner);
        resourceAsk.setConsignTime(System.currentTimeMillis());
        save(resourceAsk);
        return new ReturnBean<>(ResultCode.SUCCESS, "发货成功");
    }
    
    @Override
    public ReturnBean<String> delResourceAsk(String resourceAskID,String userID) {
        ResourceAsk resourceAsk = findOne(resourceAskID);
        if (null == resourceAsk) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "传入ID值不正确，为找到领料记录");
        }
        
        if (!resourceAsk.getAsker().equals(userID)) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "领料申请的申请人不是当前用户，当前用户不能删除！");
        }
        
        if (!resourceAsk.getStatus().equals(ResourceAskStatus.草稿.getValue())) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "领料申请已经不是草稿状态了，不允许删除");
        }
        
        iResourceAskListService.deleteByResourceAskID(resourceAskID);
        delete(resourceAskID);
        return new ReturnBean<>(ResultCode.SUCCESS, "删除成功");
    }
    
    @Override
    public ReturnBean<String> outStock(String resourceAskID) {
        return null;
    }
    
    @Override
    public ReturnBean<ResourceAsk> printConsign(String resourceAskID) {
        return null;
    }
    
    @Override
    public ReturnBean<ResourceAsk> saveResourceAsk(String resourceAskID ,List<ResourceAskList> resourceAskLists, String asker) {
        //领料申请ID
    		if (StringUtils.isNotEmpty(resourceAskID)) {
    			ResourceAsk resourceAsk = new ResourceAsk() ;
    			resourceAsk.setResourceAskID(resourceAskID);
    			resourceAsk.setResourceAskLists(resourceAskLists);
    			resourceAsk.setAsker(asker);
    			return updateResourceAsk(resourceAsk) ;
    		}
    		
    		resourceAskID = Identities.uuid2();
        ResourceAsk resourceAsk = new ResourceAsk();
        resourceAsk.setResourceAskID(resourceAskID);
        resourceAsk.setAsker(asker);
        resourceAsk.setAskTime(System.currentTimeMillis());
        resourceAsk.setStatus(ResourceAskStatus.草稿.getValue());
        resourceAsk.setAskNo(getAskNo()) ;

        save(resourceAsk);
        
        for (ResourceAskList resourceAskList : resourceAskLists) {
            resourceAskList.setResourceAskID(resourceAskID);
            resourceAskList.setResourceAskListID(Identities.uuid2());
            resourceAskList.setModifyDate(System.currentTimeMillis());
        }
        iResourceAskListService.save(resourceAskLists);
        
        resourceAsk = findOne(resourceAskID);
        
        return new ReturnBean<>(ResultCode.SUCCESS, "保存成功", resourceAsk);
    }
    
    private String getAskNo() {
    		String todayStr = LocalDate.now().toString("yyyyMMdd");
        Long lastAskNo = resourceAskRepository.findLastAskNoForEveryday(todayStr + "%");
        if (lastAskNo == null || lastAskNo == 0) {
            return todayStr + "0001";
        } else {
            lastAskNo++;
            int lastAskNoLen = 4 - String.valueOf(lastAskNo).length();
            for (int i = 0; i < lastAskNoLen; i++){
                todayStr += "0";
            }
            todayStr += lastAskNo;
            return todayStr ;
        }
    }
    
    @Override
    public ReturnBean<ResourceAsk> updateResourceAsk(ResourceAsk resourceAsk) {
        if (StringUtils.isEmpty(resourceAsk.getResourceAskID())) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "更新领料申请时，ID不能为空");
        }
        
        ResourceAsk dbResourceAsk = findOne(resourceAsk.getResourceAskID()) ;
        if (null == dbResourceAsk) {
        		return new ReturnBean<>(ResultCode.ERROR_SERVICE, "您要修改的领料申请不存在！ id = " + resourceAsk.getResourceAskID());
        }
        
        if (!dbResourceAsk.getStatus().equals(ResourceAskStatus.草稿.getValue()) && !dbResourceAsk.getStatus().equals(ResourceAskStatus.驳回.getValue())) {
	    		return new ReturnBean<>(ResultCode.ERROR_SERVICE, "您要修改的领料申请状态不是草稿或驳回，不可以修改！！ id = " + resourceAsk.getResourceAskID());
	    }
        
        dbResourceAsk.setAskTime(System.currentTimeMillis());

        iResourceAskListService.deleteByResourceAskID(resourceAsk.getResourceAskID());
        
        List<ResourceAskList> resourceAskLists = resourceAsk.getResourceAskLists();
        for (ResourceAskList resourceAskList : resourceAskLists) {
            resourceAskList.setModifyDate(System.currentTimeMillis());
            resourceAskList.setResourceAskID(resourceAsk.getResourceAskID());
            resourceAskList.setResourceAskListID(Identities.uuid2());
        }
        iResourceAskListService.save(resourceAskLists);
        
        save(dbResourceAsk);
        return new ReturnBean<>(ResultCode.SUCCESS, "更新成功", resourceAsk);
    }

    @Override
    public ReturnBean<ResourceAsk> getResourceAsk(String resourceAskID) {
    		ResourceAsk ra = resourceAskRepository.findOne(resourceAskID) ;
    		if (null == ra) {
    			 return new ReturnBean<>(501, "领料申请单不存在！ resourceAskID = " + resourceAskID);
    		}
    		
    		getResourceAskInfo(ra) ;
    		
        return new ReturnBean<>(ResultCode.SUCCESS, "领料申请单详情成功", ra);
    }

    @Override
    public ReturnBean<PageWrapper<ResourceAsk>> getResourceAskList(String askNO, String askUserID, Integer askStatus, Integer pageNum, Integer pageSize) {
        Condition condition = new Condition();
        List<FilterCondition> filterConditionList = new ArrayList<>();
        List<OrderCondition> orderConditions = new ArrayList<>();
        if (StringUtils.isNotBlank(askNO)) {
            filterConditionList.add(new FilterCondition(askNO, "askNo", ConditionRelate.and.name(), Operation.eq.name(), 1));
        }
        if (StringUtils.isNotBlank(askUserID)) {
            filterConditionList.add(new FilterCondition(askUserID, "asker", ConditionRelate.and.name(), Operation.eq.name(), 2));
        }
        if (askStatus != null && askStatus != -1) {
            filterConditionList.add(new FilterCondition(String.valueOf(askStatus), "status", ConditionRelate.and.name(), Operation.eq.name(), 3));
        }
        condition.setFilterCondition(filterConditionList);
        
        orderConditions.add(new OrderCondition("askTime",Order.desc.toString() , 1)) ;
        condition.setOrderConditions(orderConditions);
        
        condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), ResourceAsk.class).getResult();


        Sort sort = new Sort(Sort.Direction.DESC, "askNo");
        sort = sort.and(new Sort(Sort.Direction.DESC, "askTime"));
        // 获得分页对象pageable，并且在pageable中页码是从0开始，设定按照sortType升序排列
        Pageable pageable = new PageRequest(pageNum - 1, pageSize, sort);
        Page<ResourceAsk> page = resourceAskRepository.findAll(condition.getSpecification(), pageable);
        List<ResourceAsk> resourceAskList = page.getContent() ;
        List<ResourceAsk> rtnResourceAskList = new ArrayList<>() ;
        
        if (null == resourceAskList) {
        		return new ReturnBean<>(ResultCode.SUCCESS, "获取领料申请单成功！", PageHelper.toPage(page));
        }
        
        for(ResourceAsk resourceAsk:resourceAskList) {
        		resourceAsk.setStatusStr(ResourceAskStatus.getName(resourceAsk.getStatus()));
        		User user = iUserService.findOne(resourceAsk.getAsker()) ;
        		if (null != user) {
        			resourceAsk.setAskerName(user.getName());
        		}
        		
        		rtnResourceAskList.add(resourceAsk) ;
        }
        
        PageWrapper<ResourceAsk> pageRA = PageHelper.toPage(page ,rtnResourceAskList) ;
        return new ReturnBean<>(ResultCode.SUCCESS, "获取领料申请单成功！", pageRA);
    }
    
    @Override
    public ReturnBean<List<ResourceAskStatusDTO>> getResourceAskStatus() {
        List<ResourceAskStatusDTO> resourceAskStatuses = new ArrayList<>();
        for (ResourceAskStatus resourceAskStatus : ResourceAskStatus.values()) {
            resourceAskStatuses.add(new ResourceAskStatusDTO(resourceAskStatus.getValue(), resourceAskStatus.getName()));
        }
        return new ReturnBean<>(ResultCode.SUCCESS, "获取资源申请状态列表成功！", resourceAskStatuses);
    }

	@Override
	public List<ResourceAsk> findByInProcessInsID(List<String> processInsIDs) {
		return resourceAskRepository.findByProcessInsIDIn(processInsIDs) ;
	}

	@Override
	public ResourceAsk findByProcessInsID(String processInsID) {
		return resourceAskRepository.findByProcessInsID(processInsID) ;
	}

	@Override
	public List<ResourceAsk> findToDoList(String userId) {
		
		List<ResourceAsk> ras = iResourceAskFlowService.findToDoList(userId) ;
		
		if (null == ras) {
	    		return ras ;
	    }
    
	    for(ResourceAsk resourceAsk:ras) {
	    		resourceAsk.setStatusStr(ResourceAskStatus.getName(resourceAsk.getStatus()));
	    		User user = iUserService.findOne(resourceAsk.getAsker()) ;
	    		if (null != user) {
	    			resourceAsk.setAskerName(user.getName());
	    		}
	    		
	    }
	    
	    Collections.sort(ras, new Comparator<ResourceAsk>() {
	    		public int compare(ResourceAsk arg0, ResourceAsk arg1) {  
	            return arg0.getAskNo().compareTo(arg1.getAskNo());  
	        } 
	    });
    
	    Collections.reverse(ras);
	    
		return ras;
	}

	@Override
	public ReturnBean<ResourceAsk> getResourceAskForFlow(String resourceAskID) {
		ResourceAsk ra = resourceAskRepository.findOne(resourceAskID) ;
		if (null == ra) {
			 return new ReturnBean<>(501, "领料申请单不存在！ resourceAskID = " + resourceAskID);
		}
		
		if (null == ra.getTaskID()) {
			return new ReturnBean<>(612,"业务工作流任务不存在") ;
		}
		
		getResourceAskInfo(ra) ;
		
		iResourceAskFlowService.getResourceAskForFlow(ra) ;
		
		return new ReturnBean<>(ResultCode.SUCCESS, "领料申请单详情成功", ra) ; 
	}
	
	private ResourceAsk getResourceAskInfo(ResourceAsk ra) {
		
		ra.setStatusStr(ResourceAskStatus.getName(ra.getStatus()));
		
		User user = iUserService.findOne(ra.getAsker()) ;
		
		if (StringUtils.isNotEmpty(user.getOrganizationID())) {
			Organization org = iOrganizationService.findOne(user.getOrganizationID()) ;
			if (null != org) {
				ra.setOrganization(org);
			}
		}
		
		
		if (null != user) {
			ra.setAskerName(user.getName());
		}
		
		List<ResourceAskList> resourceAskLists = iResourceAskListService.findByResourceAskID(ra.getResourceAskID()) ;
	
		List<ResourceAskList> rtnResourceAskLists = new ArrayList<>() ;
		if (null == resourceAskLists) {
			 return ra ;
		}
		CommodityTerminal commodityTerminal ;
		for(ResourceAskList resourceAskList:resourceAskLists) {
			resourceAskList.setCommodity(iCommodityTmlService.findCommodityByCommodityTerminalID(resourceAskList.getCommodityTerminalID())) ;
			commodityTerminal = iCommodityTmlService.findOne(resourceAskList.getCommodityTerminalID()) ;
			resourceAskList.setCommodityTerminal(commodityTerminal) ;
			rtnResourceAskLists.add(resourceAskList) ;
		}
		
		ra.setResourceAskLists(rtnResourceAskLists);
		
		return ra ;
	}

	@Override
	public void approveResourceAsk(String resourceAskID) {
        ResourceAsk resourceAsk = findOne(resourceAskID);
        if (resourceAsk == null) {
            // 传入ID值不正确，未找到领料记录
            logger.info("传入ID值：{},不正确，未找到领料记录！", resourceAskID);
            return;
        }
        User askerUser = iUserService.findOne(resourceAsk.getAsker());
        if (askerUser == null) {
            // 传入ID值不正确，未找到领料记录
            logger.info("申请人用户记录未找到！", resourceAsk.getAsker());
            return;
        }
        
        List<ResourceAskList> resourceAskLists = iResourceAskListService.findByResourceAskID(resourceAsk.getResourceAskID()) ;
        resourceAsk.setResourceAskLists(resourceAskLists);
        
        iInStockService.inStockFromResourceAsk(resourceAsk) ;
        
        /*List<Stock> stockList = iStockService.findByWarehouseID(askerUser.getWarehouseID());
        List<ResourceAskList> resourceAskLists = iResourceAskListService.findByResourceAskID(resourceAskID);
        Map<String, Stock> stockMap = new HashMap<>();
        for (Stock stock : stockList) {
            stockMap.put(stock.getCommodityTerminalID(), stock);
        }

        List<Stock> saveStockList = new ArrayList<>();
        if (1 == askerUser.getWarehouseType()) {
            saveStockList.addAll(resourceAskLists.stream().map(resourceAskList -> getStock(stockMap, resourceAskList, askerUser.getWarehouseID())).collect(Collectors.toList()));
        } else {
            List<Warehouse> warehouseList = iWarehouseService.findByWarehouseTypeAndStatus(WarehouseType.公司总仓库.getValue().toString(),
                    CommonStatus.有效.getValue());
            if (warehouseList.size() <= 0) {
                // 未找到公司总仓库
                logger.info("未找到公司总仓库!");
                return;
            }
            String companyWarehouseID = warehouseList.get(0).getWarehouseID();
            List<Stock> companyStockList = iStockService.findByWarehouseID(companyWarehouseID);
            Map<String, Stock> companyStockMap = new HashMap<>();
            for (Stock stock : companyStockList) {
                companyStockMap.put(stock.getCommodityTerminalID(), stock);
            }
            for (ResourceAskList resourceAskList : resourceAskLists) {
                saveStockList.add(getStock(stockMap, resourceAskList, askerUser.getWarehouseID()));
                if (companyStockMap.keySet().contains(resourceAskList.getCommodityTerminalID())) {
                    Stock stock = companyStockMap.get(resourceAskList.getCommodityTerminalID());
                    Integer stockLeftNum = stock.getNum() - resourceAskList.getAskNum();
                    stock.setNum(stockLeftNum);
                    saveStockList.add(stock);
                    logger.info("申请的终端商品：{},公司总库存剩余：{}!", resourceAskList.getCommodityTerminalID(), stockLeftNum);
                } else {
                    // 未找到公司总仓库,没有执行减库存操作
                    logger.info("领料申请列表：{},未找到对应的公司总仓库,没有执行减库存操作!", resourceAskList.getResourceAskListID());
                }
            }
        }
        iStockService.save(saveStockList);*/
	}

    private Stock getStock(Map<String, Stock> stockMap, ResourceAskList resourceAskList, String warehouseID){
        Stock stock = new Stock();
        if (stockMap.keySet().contains(resourceAskList.getCommodityTerminalID())) {
            stock = stockMap.get(resourceAskList.getCommodityTerminalID());
            stock.setNum(stock.getNum() + resourceAskList.getAskNum());
        } else {
            stock.setStockID(Identities.uuid2());
            stock.setCommodityTerminalID(resourceAskList.getCommodityTerminalID());
            stock.setNum(resourceAskList.getAskNum());
            stock.setWarehouseID(warehouseID);
            stock.setModifyDate(System.currentTimeMillis());
        }
        return stock;
    }

	@Override
	public ReturnBean<String> startWorkflow(String userId, String resourceAskID ,Map<String, Object> variables) {
		
		ResourceAsk resourceAsk = this.findOne(resourceAskID) ;
		
		if(null ==  resourceAsk) {
			return  new ReturnBean<>(9010, "提交的领料申请不存在！");
		}
		
		User user = iUserService.findOne(userId) ;
		
		if(null ==  user) {
			return  new ReturnBean<>(9011, "领料申请人不存在！");
		}
		
		List<UserRole> userRoles = iUserRoleService.findByUserID(user.getUserID()) ;
		if (null==userRoles || userRoles.isEmpty()) {
			return  new ReturnBean<>(9011, "领料申请人角色设置错误！");
		}else {
			user.setRoleID(userRoles.get(0).getRoleID());
		}
		
		if (!user.getUserID().equals(resourceAsk.getAsker())) {
			return  new ReturnBean<>(9011, "当前用户不是提交的领料申请单的申请人，不能提交审核！");
		}
		
		if (user.getWarehouseFlag().equals(0)) {
			return  new ReturnBean<>(9011, "当前用户没有仓库不能申请领料！");
		}
		
		if (null == user.getWarehouseType() || StringUtils.isEmpty(user.getWarehouseID())) {
			return  new ReturnBean<>(9011, "当前用户仓库信息不完整，请联系管理员！");
		}
		
		List<ResourceAskList> resourceAskLists = iResourceAskListService.findByResourceAskID(resourceAsk.getResourceAskID()) ;
		
		if (null == resourceAskLists || resourceAskLists.isEmpty()) {
			return  new ReturnBean<>(9012, "申请单内没有商品，请至少申请一种商品方可提交！");
		}
		
		ReturnBean<String> rtn = checkStock( user , resourceAskLists) ;
		if (!rtn.getCode().equals(ReturnBean.CODE_SUCCESS)) {
			return rtn ;
		}
		
		return iResourceAskFlowService.startWorkflow(user ,resourceAskID, variables) ;
	}
	
	private ReturnBean<String> checkStock(User user ,List<ResourceAskList> resourceAskLists){
		if (user.getWarehouseType().equals(1)) {
			return  new ReturnBean<>(ReturnBean.CODE_SUCCESS, "公司库存不需要校验库存！");
		}
			
		Stock tmpStock ;
		Map<String ,Stock> map = getCompanyStockMap();
		List<String> notEnoughStock = new ArrayList<>() ;
		for(ResourceAskList resourceAskList:resourceAskLists) {
			tmpStock = map.get(resourceAskList.getCommodityTerminalID()) ;
			if(null == tmpStock || null == tmpStock.getNum()) {
				notEnoughStock.add(resourceAskList.getCommodityTerminalID()) ;
			}else {
				if (tmpStock.getNum()-resourceAskList.getAskNum()<0) {
					notEnoughStock.add(resourceAskList.getCommodityTerminalID()) ;
				}
			}
		}
		
		if (notEnoughStock.isEmpty()) {
			return  new ReturnBean<>(ReturnBean.CODE_SUCCESS, "库存充足！");
		}
		
		
		String errorStr = "" ;
		List<CommodityTerminal> commodityTerminals = iCommodityTmlService.findAll(notEnoughStock) ;
		for(CommodityTerminal commodityTerminal:commodityTerminals) {
			errorStr = errorStr + commodityTerminal.getCommodityTerminalName() + " " ;
		}
		
		return  new ReturnBean<>(9012, errorStr + "库存不足！");
		
	}
	
	
	
	private Map<String ,Stock> getCompanyStockMap(){
		Map<String ,Stock> map = new HashMap<>() ;
		Warehouse companyWarehouse = iWarehouseService.getCompanyWarehouse() ;
		List<Stock> companyStocks = iStockService.findByWarehouseID(companyWarehouse.getWarehouseID()) ;
		if (null== companyStocks || companyStocks.isEmpty()) {
			return map ;
		}
		
		for (Stock stock:companyStocks) {
			map.put(stock.getCommodityTerminalID(), stock) ;
		}
		
		return map ;
	}

    @Override
    public List<ResourceAskDTO> findByCountDate(Long countDate, Long countEndTime) {
        return resourceAskRepository.findByCountDate(countDate, countEndTime);
    }

    @Override
	public ReturnBean<ResourceAsk> addResourceAskDraft(String userID, String commodityTerminalID ,Integer askNum) {
		ResourceAsk resourceAsk = resourceAskRepository.findByAskerAndStatus(userID ,ResourceAskStatus.草稿.getValue()) ;
		ResourceAskList resourceAskList = null;
		if (null == resourceAsk) {
			resourceAsk = new ResourceAsk() ;
			resourceAsk.setResourceAskID(Identities.uuid2());
			resourceAsk.setAsker(userID);
			resourceAsk.setAskTime(System.currentTimeMillis());
	        resourceAsk.setStatus(ResourceAskStatus.草稿.getValue());
	        resourceAsk.setAskNo(getAskNo()) ;
	        resourceAskRepository.save(resourceAsk) ;
		}else {
			resourceAskList = iResourceAskListService.findByResourceAskIDAndCommodityTerminalID(resourceAsk.getResourceAskID(), commodityTerminalID) ;
		}
		
		if (null == resourceAskList) {
			resourceAskList = new ResourceAskList() ;
			resourceAskList.setResourceAskListID(Identities.uuid2());
			resourceAskList.setResourceAskID(resourceAsk.getResourceAskID());
			resourceAskList.setAskNum(askNum);
			resourceAskList.setCommodityTerminalID(commodityTerminalID);
		}else {
			resourceAskList.setAskNum(resourceAskList.getAskNum() + askNum);
		}
		
		resourceAskList.setModifyDate(resourceAsk.getAskTime());
		iResourceAskListService.save(resourceAskList) ;
		
		return this.getResourceAsk(resourceAsk.getResourceAskID());
	}
	
    @Override
	public ReturnBean<ResourceAsk> getResourceAskDraft(String userID) {
    		ResourceAsk resourceAsk = resourceAskRepository.findByAskerAndStatus(userID ,ResourceAskStatus.草稿.getValue()) ;
    		
    		if (null == resourceAsk) {
    			resourceAsk = new ResourceAsk() ;
    			resourceAsk.setResourceAskID(Identities.uuid2());
    			resourceAsk.setAsker(userID);
    			resourceAsk.setAskTime(System.currentTimeMillis());
    	        resourceAsk.setStatus(ResourceAskStatus.草稿.getValue());
    	        resourceAsk.setAskNo(getAskNo()) ;
    	        resourceAskRepository.save(resourceAsk) ;
    	        
    	        return new ReturnBean<>(ReturnBean.CODE_SUCCESS, "获取领料草稿成功" ,resourceAsk);
    		}
    		
    		return this.getResourceAsk(resourceAsk.getResourceAskID());
	}

	@Override
	public ReturnBean<String> delResourceAskList(String resourceAskListID) {
		iResourceAskListService.delete(resourceAskListID);
		
		return  new ReturnBean<>(ReturnBean.CODE_SUCCESS, "删除领料内容成功！");
	}
}
